<template>
  <div>
    <el-dialog
      title="编辑用户信息"
      :visible.sync="dialogVisible"
      width="560px"
      :before-close="closeDialog"
      :close-on-click-modal="false"
      :append-to-body="true"
    >
      <el-form
        :model="editForm"
        :rules="rules"
        ref="refForm"
        label-width="120px"
      >
        <el-form-item size="small" prop="username" label="用户名">
          <el-input
            clearable
            maxlength="18"
            v-model="editForm.username"
            placeholder="请输入"
            oninput="value=value.replace(/\s*/g,'')"
            @blur="item.username = $event.target.value"
            style="width: 90%"
          ></el-input>
        </el-form-item>

        <el-form-item size="small" prop="mobile" label="手机号">
          <el-input
            disabled
            clearable
            oninput="value=value.replace(/[^\d]/g,'')"
            @blur="item.mobile = $event.target.value"
            v-model="editForm.mobile"
            placeholder="请输入"
            maxlength="11"
            style="width: 90%"
          ></el-input>
        </el-form-item>

        <el-form-item size="small" prop="orgIdList" label="所在监控节点">
          <el-input
            @focus="innerVisible = true"
            v-model="editForm.orgName"
            placeholder="请选择"
            style="width: 90%"
            type="textarea"
            :autosize="{ minRows: 1, maxRows: 6 }"
          ></el-input>
        </el-form-item>

        <el-form-item size="small" prop="roleId" label="用户角色">
          <el-select
            v-model="editForm.roleId"
            placeholder="请选择"
            style="width: 90%"
          >
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.description"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog" class="cancel-button"
          >取 消</el-button
        >
        <el-button size="small" @click="submit" class="confirm-button"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <el-dialog
      width="600px"
      title="选择组织"
      :visible.sync="innerVisible"
      append-to-body
    >
      <div style="min-height: 55vh">
          <!--  @check-change="handleCheck" -->
        <el-tree
          :data="dataList"
          show-checkbox
          node-key="id"
          :props="defaultProps"
          ref="treeRef"
          :default-checked-keys="editForm.orgIdList"
          check-strictly
          :expand-on-click-node="false"
        >
        </el-tree>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="closetree" class="cancel-button"
          >取 消</el-button
        >
        <el-button size="small" @click="addtree" class="confirm-button"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  reqOrgEdit,
  reqRegion,
  reqRegionLevel,
  reqOrgSuperLevelInfo,
  reqOrgList,
  userAssign,
} from "@api/api.js";
import mixinRules from "./mixins/rules.js";
import { mapState } from "vuex";
import $ from "jquery";
import TreeSelSearch from "@components/TreeSelSearch.vue";
import treeselect from "@riophae/vue-treeselect"; //树形选择器
import "@components/vue-treeselect.less"; //树形选择器
import { LOAD_CHILDREN_OPTIONS } from "@riophae/vue-treeselect"; //Vue-Treeselect三级动态加载
import { handleTree, transTree } from "@utils/trans-tree";
import { validateUsername, validMobile } from "@utils/validate";

export default {
  props: ["editOrgInfo", "roleList","orgId"],
  mixins: [mixinRules],
  components: {
    TreeSelSearch,
    treeselect,
  },
  data() {
    return {
      normalizer(node) {
        return {
          id: node.id,
          label: node.orgName,
          children: node.children,
        };
      },
      defaultProps: {
        children: "children",
        label: "orgName",
      },
      provinceList: [],
      cityList: [],
      areaList: [],
      streetList: [],
      communityList: [], //社区
      dialogVisible: false,
      innerVisible: false,
      rules: {
        username: [
          {
            required: true,
            message: "请输入用户名",
            trigger: "blur",
          },
          {
            validator: validateUsername,
          },
        ],
        mobile: [
          {
            required: true,
            message: "请输入手机号",
            trigger: "blur",
          },
          {
            validator: validMobile,
          },
        ],
        orgIdList: [
          {
            required: true,
            message: "请选择监控节点",
            trigger: "change",
          },
        ],
        roleId: [
          {
            required: true,
            message: "请选择角色",
            trigger: ["blur", "change"],
          },
        ],
        orgId: [
          {
            required: true,
            message: "请选择组织机构",
            trigger: ["blur", "change"],
          },
        ],
      },
      editForm: {
        id: "",
        username: "",
        mobile: "",
        nickname: "",
        roleId: "", // 角色id
        enterpriseId: "",
        // orgId: null, //组织机构id
        orgIdList: [], //组织机构id集
        orgRole: "",
        orgName: "",
      },
      reqUrl:
        "https://apis.map.qq.com/tools/locpicker?search=1&type=1&key=44FBZ-OVKKP-T23D5-VGHUE-XDXC3-BDF53&referer=精卫安管理系统&policy=1",
      isShowMap: false,
      LocationInfo: true, //判断是否从地图选的经纬度
      activeNames: ["1"],
      dataList: [],
    };
  },
  computed: {
    ...mapState(["user", "spacesManage"]),
  },
  watch: {
    dialogVisible: {
      handler(val) {
        if (val) {
          this.editForm.username = this.editOrgInfo.username;
          this.editForm.mobile = this.editOrgInfo.mobile;
          this.editForm.roleId = this.editOrgInfo.role.id;
          this.editForm.orgIdList = this.editOrgInfo.orgId.split(",");
          this.editForm.orgName = this.editOrgInfo.orgName;
          // this.editForm.orgIdList = this.editOrgInfo.orgIdList;
          // this.editForm.orgIdList =['1877624287093932033']
        }
      },
    },
  },
  methods: {
    // 监听 check 事件，手动处理父节点勾选时的子节点联动
    handleCheck(data, checked) {
      // 当前节点被勾选
      if (checked) {
        // 如果是父节点，勾选所有子节点
        if (!data.hasChildren || data.hasChildren == 1) {
          this.setChildrenChecked(data, true);
        }
      } else {
        // 如果取消勾选，递归取消子节点
        if (!data.hasChildren || data.hasChildren == 1) {
          this.setChildrenChecked(data, false);
        }
      }
    },
    async setChildrenChecked(children, isChecked) {
      // console.log(children,'children');
      let params = {
        tenantId: this.user.tenantId,
        userId: this.user.userId,
        roleName: this.user.roleName,
        parentId: children.id,
        type:"1,2,3"
      };
      let res = await reqOrgList( params);
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      // console.log(res.data.rows, "res.data.rows");
      res.data.rows.forEach((child) => {
        this.$refs.treeRef.setChecked(child, isChecked);
        if (child.hasChildren == 1) {
          // 有子级
          this.setChildrenChecked(child, isChecked);
        }
      });
    },
    addtree() {
      const checkedNodes = this.$refs.treeRef.getCheckedNodes();
      this.editForm.orgName = checkedNodes
        .map((node) => node.orgName)
        .join("，");
      // 提取选中节点的 id
      this.editForm.orgIdList = checkedNodes.map((node) => node.id);
      // console.log( this.editForm.orgIdList,' this.editForm.orgIdList');
      this.innerVisible = false;
    },
    closetree() {
      this.innerVisible = false;
    },
    // 选择一条
    handleSelect(node, instanceId) {
      //   console.log("选中的节点:", node);
      this.editForm.orgIdList = [node.id];
      //   console.log(this.editForm.orgIdList);
    },
    async OrgList() {
      var res = await reqOrgList({
        userId: this.user.userId,
        roleName: this.user.roleName,
        tenantId: this.user.tenantId,
        orgName: "",
        parentId: "",
        type:"1,2,3"
      });
      // console.log(res, "res");
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      let { rows } = res.data;
      this.dataList = transTree(rows);//返回全部数据
    },
    // 点击编辑
    submit() {
      this.$refs.refForm.validate(async (valid) => {
        if (!valid) return;
        const res = await userAssign({
          userId: this.editOrgInfo.userId,
          orgIdList: this.editForm.orgIdList,
          roleId: this.editForm.roleId,
          username: this.editForm.username,
          orgId: this.orgId,
        });
        if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
        this.$modal.notifySuccess("编辑成功");
        this.$parent.getInitDataList();
        this.closeDialog();
      });
    },
    // 点击关闭弹框
    closeDialog() {
      this.$refs.refForm.resetFields();
      this.dialogVisible = false;
      this.areaList = [];
      this.streetList = [];
      this.cityList = [];
      this.communityList = [];
      this.editForm = {
        id: "",
        username: "",
        mobile: "",
        nickname: "",
        roleId: "", // 角色id
        enterpriseId: "",
        orgIdList: [], //组织机构id集
        orgRole: "",
        orgName: "",
      };
    },
  },
};
</script>

<style lang="less" scoped>
@import url("~@views/style/tablePage.less");
@import url("../../../common.less");

.mapLoc {
  height: 60vh;
  width: 100%;
  overflow-y: hidden;

  .iframe {
    width: 100%;
    height: 100%;
  }
}

.zuobiao {
  color: @primaryTxtcolor;
}

// 树形
.el-tree {
  background: @primaryTree;
}

// 树形控件字体颜色
::v-deep .el-tree-node__content {
  color: @primaryTree2 !important;
}

// 树形控件选中一行的字体颜色
::v-deep .el-tree-node.is-current > .el-tree-node__content {
  color: #000 !important;
}

::v-deep .el-tree {
  height: 100%;
  font-size: 14px;
  background: @primaryHeaderBgcolor;
  box-sizing: border-box;
  padding: 12px 10px;
  color: @primaryThemeTxtColor;
  overflow: hidden;
  overflow-y: scroll;
}

::v-deep .el-tree-node__content {
  // padding: 5px 0 !important;
  &:hover {
    background: @paginationBgcolor !important;
    border-radius: 4px;
  }
}

::v-deep .el-tree-node.is-focusable > .el-tree-node__content {
  padding: 5px 0;
}

// 解决收起后白色背景问题
::v-deep .el-tree-node.is-expanded > .el-tree-node__content {
  background-color: transparent;
}

// 解决展开后白色背景问题
::v-deep .el-tree-node.is-focusable > .el-tree-node__content {
  background-color: transparent;
  border-radius: 4px;
}

::v-deep .is-current > .el-tree-node__content > .el-tree-node__label {
  color: #f0f0f0;
}
</style>
